<template>
	<view>
		<view class="detailArea">
			<!-- 标题放在bar上面,传参也行,搜完之后设置也行 -->
			<view class="detailItem">
				<!-- 轮播图 -->
				<swiper indicator-dots>
					<swiper-item v-for="(item,index) in swipers" :key="index">
						<image :src="item"></image>
					</swiper-item>
				</swiper>

				<text>类型:</text>
				<uni-card>
					<text>{{type}}</text>
				</uni-card>
				<text>时间:</text>
				<uni-card>
					<text>{{beginTime}}~{{endTime}}</text>
				</uni-card>
				<text>地点:</text>
				<uni-card>
					<text>{{place}}</text>
				</uni-card>
				<text>详情:</text>
				<uni-card>
					<text>{{content}}</text>
				</uni-card>
				<!-- 阅读数-start -->
				<text class="top-read-before">加入日程数：</text>
				<span class="top-read">{{addedTimes}}</span>
			</view>

		</view>

		<!-- 分割线  -->
		<view class="line"></view>
		<view class="summarizeTitle">评论区</view>
		<view class="line"></view>

		<!-- 评论区  -->
		<view class="comment-eg">

			<hb-comment ref="hbComment" @add="add" @del="del" @like="like" @focusOn="focusOn" :deleteTip="'确认删除？'"
				:cmData="commentData" v-if="commentData"></hb-comment>

		</view>

		<!-- 底部按钮 -->
		<view class="bottom_nav">
			<uni-goods-nav :fill="true" :options="options" :button-group="buttonGroup" @buttonClick="bottomBtn">
			</uni-goods-nav>

		</view>

	</view>
</template>

<script>
	
	Date.prototype.Format = function (fmt) {
	    var o = {
	        "M+": this.getMonth() + 1, // 月份
	        "d+": this.getDate(), // 日
	        "h+": this.getHours(), // 小时
	        "m+": this.getMinutes(), // 分
	        "s+": this.getSeconds(), // 秒
	        "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
	        "S": this.getMilliseconds() // 毫秒
	    };
	    if (/(y+)/.test(fmt))
	        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	    for (var k in o)
	        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	            return fmt;
	}

	export default {
		data() {
			return {
				apiUrl: "http://localhost:8080/",
				detailUrl: "activity/",
				uid: 7,
				aid: 18,
				activityName: "",
				type: "",
				place: "",
				beginTime: "",
				endTime: "",
				content: "",
				addedTimes: 0,
				swipers: [],
				"commentData": null,
				"reqFlag": false, // 请求标志，防止重复操作，true表示请求中
				options: [],
				buttonGroup: [{
						text: '发表评论',
						backgroundColor: '#7cffe5',
						color: '#fff',

					},
					{
						text: '加入日程',
						backgroundColor: '#ffa200',
						color: '#fff'
					}
				]

			}
		},
		/* 
				onShow() {
					
				}, */
		onLoad() {
			uni.setStorageSync("token", "Bearer " +
				"eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhYWEiLCJleHAiOjE2NzEwMjc2ODksImlhdCI6MTY3MTAwOTY4OX0.GE97tpDrkOy8qmXd4hTIewWnkBkQFYFWYj2_FhDndoQkW7Dz153ojM1fXtHr04rGENjFhYrFgkiGnTJJDMp8kA"
				)
			this.getActivityDetail();
			this.getComment();
		},
		// 以后去掉注释
		// onLoad(options) {

		// 	this.uid = options.uid;
		// 	this.aid = options.aid;
		// 	this.activityName = options.name;
		// 	/* uni.setNavigationBarTitle({
		// 		title:options.name
		// 	}) */
		// 	this.getActivityDetail();
		//  this.getComment();
		// },
		methods: {
			getActivityDetail() {
				//获取活动信息
				uni.request({
					method: 'GET',
					url: 'http://localhost:8080/activity/' + this.aid,

					header: {
						Authorization: uni.getStorageSync("token")
						// Authorization: "Bearer " +
						// 	"eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJoenMiLCJleHAiOjE2NzA5NDQ1NzMsImlhdCI6MTY3MDkyNjU3M30.2xSkDjb5b8gE-NAd-YdxP3LgewgVo1H6ncx1QCcujTQu2V248kRrjygb544cWQmsuPpzH3jwbNPQqQwtAlFCeQ"

					},
					success: (res) => {
						console.log(res);
						this.activityName = res.data.name;
						this.content = res.data.content;
						this.beginTime = res.data.beginTime;
						this.endTime = res.data.endTime;
						this.type = res.data.type;
						this.place = res.data.place;
						if (res.data.pic1) {
							this.swipers.push(res.data.pic1);
						}
						if (res.data.pic2) {
							this.swipers.push(res.data.pic2);
						}
						if (res.data.pic3) {
							this.swipers.push(res.data.pic3);
						}
						console.log(this.swipers);
					},
					fail: (err) => {
						return uni.showToast({
							icon: 'loading',
							title: '请求失败'
						})
						reject(err)
					}
				})
			},
			addToCalender() {
				console.log("加入日程");
				//调用函数,加入到日程中
				uni.request({
					method: 'POST',
					url: this.apiUrl + "schedule/add",
					header: {
						Authorization: uni.getStorageSync("token"),
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					data: {
						'uid': this.uid,
						'activityId': this.aid
					},
					success: (res) => {
						console.log(res.data);
						//提示成功加入
					},
					fail: (err) => {
						return uni.showToast({
							icon: 'loading',
							title: '请求失败'
						})
						reject(err)
					}
				})
			},
			getComment() {
				//获取所有评论，后端返回CommentDTO
				uni.request({
					method: 'GET',
					url: "http://localhost:8080/comment/getComment/" + this.aid,
					header: {
						Authorization: uni.getStorageSync("token")
					},
					success: (res) => {
						console.log(res.data);
						let comments = res.data;
						let size = comments.length;
						let commentList = [];
						console.log(size);
						for (let i = 0; i < size; i++, this.count++) {

							// 对搜索到的评论加入commentList,只有fromUid与自己uid一致时,"owner": true,
							let owner = false;
							if (comments[i].fromUid == this.uid) {
								owner = true;
							}
							// hasLike(该用户是否给这个评论点过赞,后端实现了吗?)要怎么存啊?这里先全部false
							commentList.push({
								"id": comments[i].id,
								"uid": comments[i].fromUid,
								"owner": owner,
								"hasLike": false,
								"likeNum": comments[i].likes,
								"avatarUrl": comments[i].picture,
								"nickName": comments[i].fromName,
								"content": comments[i].content,
								"parentId": comments[i].parentId,
								"createTime": comments[i].time,
								"type":comments[i].type
							});
						}
						console.log(commentList);
						// console.log(this.getTree(commentList));
						this.commentData = {
							"commentSize": commentList.length,
							"comment": this.getTree(commentList)
						};
					},
					fail: (err) => {
						return uni.showToast({
							icon: 'loading',
							title: '请求失败'
						})
						reject(err)
					}
				})
			},
			dynamicComment(content) {
				//新增一级评论
				var time = new Date().Format("yyyy-MM-dd hh:mm:ss");
				console.log(time);
				uni.request({
					method: 'POST',
					url: this.apiUrl + "comment",
					header: {
						Authorization: uni.getStorageSync("token")
					},
					data: {
						"type": "dynamic",
						"parentId": this.aid,
						"fromUid": this.uid,
						"toUid": -1, //修改
						"content": content,
						"time": time,
						"likes": 0
					},
					success: (res) => {
						console.log(res.data);
						// this.getComment();
					},
					fail: (err) => {
						return uni.showToast({
							icon: 'loading',
							title: '请求失败'
						})
						reject(err)
					}
				})
			},
			simpleComment(parentId, content, toUid) {
				//新增二级评论
				var time = new Date().Format("yyyy-MM-dd hh:mm:ss");
				console.log(time);
				uni.request({
					method: 'POST',
					url: this.apiUrl + "comment",
					header: {
						Authorization: uni.getStorageSync("token")
					},
					data: {
						"type": "comment",
						"parentId": parentId, //不确定是什么
						"fromUid": this.uid,
						"toUid": toUid, //待修改
						"content": content,
						"time": time,
						"likes": 0,
						"needCheck":false
					},
					success: (res) => {
						console.log(res.data);
						this.getComment();
					},
					fail: (err) => {
						return uni.showToast({
							icon: 'loading',
							title: '请求失败'
						})
						reject(err)
					}
				})

			},
			likeComment(id) {
				//点赞评论
				uni.request({
					method: 'PUT',
					url: this.apiUrl + "comment/like/" + id,
					header: {
						Authorization: uni.getStorageSync("token")
					},
					success: (res) => {
						console.log(res.data);
						// this.getComment();
					},
					fail: (err) => {
						return uni.showToast({
							icon: 'loading',
							title: '请求失败'
						})
						reject(err)
					}
				})
			},
			deleteComment(id) {
				//删除评论
				uni.request({
					method: 'DELETE',
					url: this.apiUrl + "comment/" + id,
					header: {
						Authorization: uni.getStorageSync("token")
					},
					success: (res) => {
						console.log(res.data);
						// this.getComment();
					},
					fail: (err) => {
						return uni.showToast({
							icon: 'loading',
							title: '请求失败'
						})
						reject(err)
					}
				})
			},
			bottomBtn(e) {
				console.log(e);
				if (e.index == 0) {
					// this.toggleMask('show');
					this.$refs.hbComment.commentInput();
				} else {
					this.addToCalender();
				}
			},
			focusOn() {
				// 点击回复,如果没用可以删掉
				console.log("输入框弹出");
			},
			// 新增回复
			add(req) {
				if (this.reqFlag) {
					uni.showToast({
						title: '操作频繁',
						duration: 1000
					});
					return
				}
				this.reqFlag = true;
				console.log(req.content);
				console.log(req.pId);
				console.log(req.pUid);
				// 发送请求
				if (req.pId == null) {
					console.log("发布一级评论");
					this.dynamicComment(req.content);
				} else {
					console.log("发布二级评论");
					this.simpleComment(req.pId, req.content, req.pUid);
				}
				// 可以处理一下,如果请求失败
				// 下边假装请求成功
				this.reqFlag = false;
				this.$refs.hbComment.addComplete();

			},
			// 点赞评论
			like(commentId) {
				if (this.reqFlag) {
					uni.showToast({
						title: '操作频繁',
						duration: 1000
					});
					return
				}
				this.reqFlag = true;
				console.log(commentId);
				this.likeComment(commentId);
				this.reqFlag = false;
				// this.getComment();
				this.$refs.hbComment.likeComplete(commentId);
			},
			// 删除评论
			del(commentId) {
				if (this.reqFlag) {
					uni.showToast({
						title: '操作频繁',
						duration: 1000
					});
					return
				}
				this.reqFlag = true;
				console.log(commentId);
				this.deleteComment(commentId);
				//可以判断下是否成功

				this.reqFlag = false;
				// this.getComment();
				this.$refs.hbComment.deleteComplete(commentId);
			},
			// 列表按照父子转换成树
			getTree(data) {
				let result = [];
				let map = {};
				data.forEach(item => {
					map[item.id] = item;
				});
				data.forEach(item => {
					let parent = null;
					if(item.type == "comment"){
						parent = map[item.parentId];
					}
					
					if (parent) {
						(parent.children || (parent.children = [])).push(item);
					} else {
						result.push(item);
					}
				});
				return result;
			}

		}
	}
</script>

<style lang="scss">
	.container {
		padding: 20px;
		font-size: 14px;
		line-height: 24px;
	}
	
	.detailArea{
		// padding-bottom: 50px;
		position: relative;
	}
	
	.detailArea image{
		position: absolute;
		left:0;right:0;top:0;bottom:0;margin:auto
	}
	
	.top-read {
		font-size: 28rpx;
		padding-left: 10rpx;
		color: #999999;
	}
	
	.top-read-before {
		font-size: 28rpx;
	
	}
	
	.comment-eg{
		padding-bottom: 25px;
	}
	
	.summarizeTitle {
		height: auto;
		color: #3baacc;
		text-align: center;
		letter-spacing: 20px;
		margin: 4px 0;
	}
	
	.line {
		height: 10rpx;
		// width: 750rpx;
		background: #eee;
		letter-spacing: 20px;
		margin: 4px 0;
	}
	
	.bottom_nav {
		position: fixed;
		bottom: 0;
		left:0;
		width: 100%;
	}
</style>
